package com.boom.monitor.util;

import com.boom.monitor.DTO.SnmpDTO;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.DefaultPDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

import java.io.IOException;
import java.util.List;

/**
 * @author:yzw
 * @Date:2021/2/22 下午5:10
 * @desc:
 * @version:1.0
 */
public class SnmpUtils {

	private static CommunityTarget getTarget(SnmpDTO dto) {
		CommunityTarget target = new CommunityTarget(GenericAddress.parse("udp:" + dto.getIp() + "/" + dto.getPort())
				, new OctetString(dto.getCommunity()));
		target.setVersion(SnmpConstants.version2c);
		target.setTimeout(2000);
		target.setRetries(1);
		return target;
	}

	/**
	 * @param dto
	 * @return org.snmp4j.PDU
	 * @desc 获取查询结果，请求方式为get
	 * @author yzw
	 * @time 2021/2/23 下午5:27
	 */
	public static PDU getPduResponse(SnmpDTO dto, List<String> oIds) {
		DefaultUdpTransportMapping transport = null;
		Snmp snmp = null;
		try {
			transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
			//创建对象request
			PDU request = new PDU();
			//设置类型-GET
			request.setType(PDU.GET);
			for (String oId : oIds) {
				request.add(new VariableBinding(new OID(oId)));
			}
			//创建并初始化对象:响应事件
			ResponseEvent respEvent = snmp.send(request, getTarget(dto));
			//创建对象response接收响应
			return respEvent.getResponse();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (transport != null) {
					transport.close();
				}
				if (snmp != null) {
					snmp.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * @param dto
	 * @param oIds
	 * @return java.util.List<org.snmp4j.util.TableEvent>
	 * @desc 获取查询结果，请求方式为walk
	 * @author yzw
	 * @time 2021/2/23 下午5:53
	 */
	public static List<TableEvent> walkResponseTableEvents(SnmpDTO dto, List<String> oIds) {
		DefaultUdpTransportMapping transport = null;
		Snmp snmp = null;
		try {
			transport = new DefaultUdpTransportMapping();
			snmp = new Snmp(transport);
			snmp.listen();
			TableUtils tableUtils = new TableUtils(snmp, new DefaultPDUFactory(PDU.GET));
			OID[] columns = new OID[oIds.size()];
			for (int i = 0; i < oIds.size(); i++) {
				columns[i] = new OID(oIds.get(i));
			}
			return tableUtils.getTable(getTarget(dto), columns, null, null);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (transport != null) {
					transport.close();
				}
				if (snmp != null) {
					snmp.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
